package com.itheima.service.impl;

import com.itheima.dao.IUserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.domain.PageBean;
import com.itheima.domain.User;
import com.itheima.service.IUserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements IUserService {
    private IUserDao dao = new UserDaoImpl();

    @Override
    public List<User> FindAll() {
        //直接调用Dao中的查询所有的方法
        List<User> users = dao.FindAll();
        //将结果返回到servlet
        return users;
    }

    @Override
    public int addUser(User user) {
        //调用add方法
        int index = dao.addUser(user);
        return index;
    }

    @Override
    public int deleteUser(String id) {
        int index = dao.deleteUser(Integer.parseInt(id));
        return index;

    }

    @Override
    public User findUserById(String id) {
        User user=dao.findUserById(Integer.parseInt(id));
        return user;
    }

    @Override
    public User update(User user) {
        User updateUser =dao.update(user);
        return updateUser;
    }

    @Override
    public void deleteUsers(String[] ids) {
        for (String id : ids) {
            dao.deleteUser(Integer.parseInt(id));
        }
    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
        //1.将字符串类型的_currentPage, _row转为int类型
        int currentPage = Integer.parseInt(_currentPage);
        int rows = Integer.parseInt(_rows);

        //2.创建PageBean对象
        PageBean<User> pb =new PageBean<User>();

       //3.给pb对象赋值，两个参数currentPage和row
        pb.setCurrentPage(currentPage);
        pb.setRows(rows);

        //4.调用dao中查询总记录的方法
        int totalCount = dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);

        //5.计算开始的记录检索
        int start =(currentPage-1)*rows;

        //6.调用dao的list集合
        List<User> list  =  dao.findUserByPage(start,rows,condition);
        pb.setList(list);

        //计算总页码
        int totalPage =(int) Math.ceil(totalCount*(1.0)/rows);
        pb.setTotalCount(totalCount);
        //System.out.println(totalPage);
        pb.setTotalPage(totalPage);
        return pb;
    }


}
